package com.sa.token.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sa.token.dto.request.role.SetRoleRequest;
import com.sa.token.dto.request.user.UpdatePwdRequest;
import com.sa.token.dto.request.user.UserInfoRequest;
import com.sa.token.dto.response.authority.AuthorityInfoResponse;
import com.sa.token.dto.response.user.UserInfoResponse;
import com.sa.token.entity.SysUserEntity;
import com.sa.token.entity.SysUserInfoEntity;
import com.sa.token.entity.SysUserRoleEntity;
import com.sa.token.mapper.SysUserInfoMapper;
import com.sa.token.message.Result;
import com.sa.token.message.StandardResponse;
import com.sa.token.service.SysUserInfoService;
import com.sa.token.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

import static com.sa.token.utils.Md5Util.MD5Encode;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xhs
 * @since 2021-08-27
 */
@Service
public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUserInfoEntity> implements SysUserInfoService {
    @Autowired
    private BaseServiceImpl baseService;
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SysUserRoleService userRoleService;

    /**
     * 头像-男
     */
    @Value("${user.man-avatar}")
    private String manAvatar;

    /**
     * 头像-女
     */
    @Value("${user.girl-avatar}")
    private String girlAvatar;

    /**
     * 完善用户信息
     *
     * @param userInfoRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse insertUserInfo(UserInfoRequest userInfoRequest) {
        // 获取当前用户信息
        SysUserInfoEntity infoEntity = baseService.getSysUserInfo();
        // 头像
        String avatar = "";
        if("1".equals(userInfoRequest.getSex())){
            avatar = manAvatar;
        }else {
            avatar = girlAvatar;
        }
        // 1.查看是否已完善信息
        if (infoEntity == null) {
            // 新增用户信息
            SysUserInfoEntity userInfoEntity = SysUserInfoEntity.builder().loginId(StpUtil.getLoginIdAsString())
                    .userName(userInfoRequest.getUserName())
                    .birthday(DateUtil.parse(userInfoRequest.getBirthday()))
                    .mobilePhone(userInfoRequest.getMobilePhone())
                    .mailbox(userInfoRequest.getMailbox())
                    .creator(StpUtil.getLoginIdAsString())
                    .userPicture(avatar)
                    .build();
            boolean save = save(userInfoEntity);
            if (save) {
                return StandardResponse.build(Result.ADD_SUCCESS);
            } else {
                return StandardResponse.build(Result.ADD_ERROR);
            }
        } else {
            // 更新用户信息
            infoEntity.setUserName(userInfoRequest.getUserName());
            infoEntity.setBirthday(DateUtil.parse(userInfoRequest.getBirthday()));
            infoEntity.setSex(userInfoRequest.getSex());
            infoEntity.setUserPicture(avatar);
            infoEntity.setMobilePhone(userInfoRequest.getMobilePhone());
            infoEntity.setMailbox(userInfoRequest.getMailbox());
            infoEntity.setUpdater(infoEntity.getLoginId());
            boolean updateById = updateById(infoEntity);
            if (updateById) {
                return StandardResponse.build(Result.UPD_SUCCESS);
            } else {
                return StandardResponse.build(Result.UPD_ERROR);
            }
        }
    }

    /**
     * 获取用户信息及权限
     *
     * @return
     */
    @Override
    public StandardResponse getUserInfo() {
        // 获取当前用户信息
        SysUserInfoEntity sysUserInfo = baseService.getSysUserInfo();

        if (sysUserInfo != null) {
            UserInfoResponse userInfoResponse = UserInfoResponse.builder()
                    .userId(String.valueOf(sysUserInfo.getId()))
                    .loginId(sysUserInfo.getLoginId())
                    .userName(sysUserInfo.getUserName())
                    .userPicture(sysUserInfo.getUserPicture())
                    .birthday(DateUtil.format(sysUserInfo.getBirthday(), "yyyy-MM-dd"))
                    .mailbox(sysUserInfo.getMailbox())
                    .mobilePhone(sysUserInfo.getMobilePhone())
                    .sex(sysUserInfo.getSex())
                    .build();
            AuthorityInfoResponse userAuthority = new AuthorityInfoResponse();
            userAuthority.setUserInfo(userInfoResponse);
            return StandardResponse.build(Result.QUERY_SUCCESS).setData(userAuthority);
        } else {
            UserInfoResponse userInfoResponse = UserInfoResponse.builder().loginId(StpUtil.getLoginIdAsString()).build();
            AuthorityInfoResponse userAuthority = new AuthorityInfoResponse();
            userAuthority.setUserInfo(userInfoResponse);
            return StandardResponse.build(Result.QUERY_SUCCESS).setData(userAuthority);
        }
    }

    /**
     * 修改密码
     *
     * @param updatePwdRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse updatePwd(UpdatePwdRequest updatePwdRequest) {
        // 1.验证二次输入的密码是否一致
        if (!updatePwdRequest.getNewPwd().equals(updatePwdRequest.getConfirmPwd())) {
            return StandardResponse.build(Result.UPD_PWD_TWO_ERROR);
        }
        SysUserEntity sysUser = baseService.getSysUser();
        if (sysUser != null) {
            // 2.验证旧密码是否正确
            if (MD5Encode(updatePwdRequest.getOldPwd()).equals(sysUser.getPassword())) {
                // 3.新密码和旧密码不能一样
                if (MD5Encode(updatePwdRequest.getNewPwd()).equals(sysUser.getPassword())) {
                    return StandardResponse.build(Result.UPD_PWD_OLDANDNEW_ERROR);
                }
                // 4.更新密码
                sysUser.setPassword(MD5Encode(updatePwdRequest.getNewPwd()));
                sysUser.setUpdater(sysUser.getLoginId());
                boolean update = sysUserService.updateById(sysUser);
                if (update) {
                    // 密码更新重新提示重新登录
                    StpUtil.logout();
                    return StandardResponse.build(Result.UPD_SUCCESS);
                } else {
                    return StandardResponse.build(Result.UPD_ERROR);
                }
            } else {
                return StandardResponse.build(Result.UPD_PWD_ERROR);
            }
        }
        return StandardResponse.build(Result.UPD_ERROR);
    }

    /**
     * 编辑用户信息
     *
     * @param userInfoRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse updateUserInfo(UserInfoRequest userInfoRequest) {
        // 验证用户信息是否存在
        LambdaQueryWrapper<SysUserInfoEntity> queryWrapper = new QueryWrapper<SysUserInfoEntity>().lambda()
                .eq(SysUserInfoEntity::getLoginId, userInfoRequest.getLoginId());
        SysUserInfoEntity infoEntity = getBaseMapper().selectOne(queryWrapper);
        if (infoEntity == null) {
            SysUserInfoEntity build = SysUserInfoEntity.builder()
                    .loginId(userInfoRequest.getLoginId())
                    .userName(userInfoRequest.getUserName())
                    .birthday(DateUtil.parse(userInfoRequest.getBirthday()))
                    .sex(userInfoRequest.getSex())
                    .mobilePhone(userInfoRequest.getMobilePhone())
                    .mailbox(userInfoRequest.getMailbox())
                    .creator(StpUtil.getLoginIdAsString())
                    .build();
            // 新增用户信息
            boolean save = save(build);
            if (save) {
                return StandardResponse.build(Result.ADD_SUCCESS);
            } else {
                return StandardResponse.build(Result.ADD_ERROR);
            }
        } else {
            SysUserInfoEntity build = SysUserInfoEntity.builder()
                    .id(infoEntity.getId())
                    .userName(userInfoRequest.getUserName())
                    .birthday(DateUtil.parse(userInfoRequest.getBirthday()))
                    .sex(userInfoRequest.getSex())
                    .mobilePhone(userInfoRequest.getMobilePhone())
                    .mailbox(userInfoRequest.getMailbox())
                    .updater(StpUtil.getLoginIdAsString())
                    .build();
            // 更新用户信息
            boolean updateById = updateById(build);
            if (updateById) {
                return StandardResponse.build(Result.UPD_SUCCESS);
            } else {
                return StandardResponse.build(Result.UPD_ERROR);
            }
        }
    }

    /**
     * 设置角色
     *
     * @param setRoleRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StandardResponse setRole(SetRoleRequest setRoleRequest) {
        // 清空之前的角色
        LambdaQueryWrapper<SysUserRoleEntity> queryWrapper = new QueryWrapper<SysUserRoleEntity>().lambda()
                .eq(SysUserRoleEntity::getUserId, setRoleRequest.getUserId());
        userRoleService.remove(queryWrapper);
        // 新增角色
        ArrayList<SysUserRoleEntity> userRoleList = new ArrayList<>();
        for (String roleId : setRoleRequest.getRoleId()) {
            // 设置角色
            SysUserRoleEntity sysUserRoleEntity = SysUserRoleEntity.builder()
                    .userId(Integer.valueOf(setRoleRequest.getUserId()))
                    .roleId(Integer.valueOf(roleId))
                    .build();
            userRoleList.add(sysUserRoleEntity);
        }
        boolean save = userRoleService.saveBatch(userRoleList);
        if (save) {
            return StandardResponse.build(Result.SET_ROLE_SUCCESS);
        } else {
            return StandardResponse.build(Result.SET_ROLE_ERROR);
        }
    }
}
